package com.open4cn.simulator.core.device;

import com.open4cn.simulator.core.connector.IConnector;

import java.io.Serializable;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-04-04 11:35
 */
public abstract class AbstractDevice implements IDevice, Serializable {

    private DeviceInfo deviceInfo;

    private IConnector connector;


    @Override
    public String getId() {
        return null != deviceInfo ? deviceInfo.getId() : null;
    }

    @Override
    public IConnector getConnector() {
        return connector;
    }

    public void setConnector(IConnector connector) {
        this.connector = connector;
    }

    @Override
    public DeviceStatus getDeviceStatus() {
        return null != deviceInfo ? deviceInfo.getDeviceStatus() : null;
    }


    @Override
    public DeviceInfo getDeviceInfo() {
        return deviceInfo;
    }

    @Override
    public boolean start() {
        DeviceStatus deviceStatus = getDeviceStatus();

        // 暂停则重启
        if (deviceStatus.isSuspended()) {
            deviceStatus.beRun();
        }

        if (deviceStatus.runable()) {
            deviceStatus.beConnecting();
            IConnector connector = getConnector();
            DeviceInfo deviceInfo = getDeviceInfo();
            connector.connect(deviceInfo.getConnectAddress());
            deviceStatus.beRun();
        }
        return deviceStatus.isRunning();
    }

    @Override
    public boolean suspend() {
        DeviceStatus deviceStatus = getDeviceStatus();
        if (!deviceStatus.isSuspended()) {
            return deviceStatus.beSuspended();
        }
        return false;
    }

    @Override
    public boolean stop() {
        DeviceStatus deviceStatus = getDeviceStatus();
        if (!deviceStatus.isClosed()) {
            IConnector connector = getConnector();
            if (connector.close()) {
                deviceStatus.beClose();
            }
        }
        return deviceStatus.isClosed();
    }

    public void setDeviceInfo(DeviceInfo deviceInfo) {
        this.deviceInfo = deviceInfo;
    }

    @Override
    public boolean destroy() {
        DeviceStatus deviceStatus = getDeviceStatus();
        if (!deviceStatus.isClosed()) {
            stop();
        }
        if (deviceStatus.isClosed()) {
            getConnector().destroy();
            fieldsToNull();
            return true;
        }
        return false;
    }

    /**
     * 属性字段设置成null
     */
    private void fieldsToNull() {
        setConnector(null);
        setDeviceInfo(null);
    }
}
